﻿using Ops.Host.Common.Extensions;
using Ops.Host.Core.Models;

namespace Ops.Host.Core.Services.Impl;

internal sealed class AlarmRecordService : IAlarmRecordService
{
    private readonly IFreeSql _freeSql;

    public AlarmRecordService(IFreeSql freeSql)
    {
        _freeSql = freeSql;
    }

    public (List<AlarmRecord> items, long count) GetPaged(AlarmRecordFilter filter, int pageIndex, int pageItems)
    {
        var items = _freeSql.Select<AlarmRecord>()
                            .WhereIf(!string.IsNullOrEmpty(filter.Station), s => s.Station == filter.Station)
                            .WhereIf(!string.IsNullOrEmpty(filter.Classify), s => s.Classify == filter.Classify)
                            .WhereIf(!string.IsNullOrEmpty(filter.Desc), s => s.Desc!.Contains(filter.Desc!))
                            .WhereIf(filter.CreatedTimeStart != null, s => s.CreatedAt >= filter.CreatedTimeStart.ToDayMin())
                            .WhereIf(filter.CreatedTimeEnd != null, s => s.CreatedAt <= filter.CreatedTimeEnd.ToDayMax())
                            .OrderByDescending(s => s.CreatedAt)
                            .Count(out var total)
                            .Page(pageIndex, pageItems)
                            .ToList();
        return (items, total);
    }

    public async Task AddAlarmsAsync(IEnumerable<AlarmRecord> alarms)
    {
        await _freeSql.Insert<AlarmRecord>(alarms).ExecuteAffrowsAsync();
    }
}
